// @Date         2021-12-09
// @Author       Aaron Zhang
// @Description	  验证结构体，并返回可读性的错误
// @FileName      valid_struct.go

package common

import (
	"bytes"
	"context"
	"github.com/go-playground/validator/v10"
	"github.com/nicksnyder/go-i18n/i18n"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"zin/app/http/api_error"
	"zin/framework/gin"
	"zin/framework/util"
)

// ShouldBindJson JSON格式验证
func ShouldBindJson(c *gin.Context, data interface{}, fieldMap FieldMap) bool {
	body, _ := ioutil.ReadAll(c.Request.Body)
	if string(body) == "" {
		c.Json400Interface(api_error.ResponseParamError.SetMessage("body内容为空"))
		return false
	}

	c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))

	err := c.ShouldBindJSON(data)
	if err != nil && fieldMap != nil {
		ValidStructTrans(c, err, fieldMap)
		return false
	}
	return true
}

// ValidStructTrans c.BindJson返回的错误，进行翻译成容易理解的表达方式
func ValidStructTrans(c *gin.Context, err error, fieldMapInterface FieldMap) {
	//类型断言
	errs := err.(validator.ValidationErrors)

	//翻译文件所在位置
	transFile := filepath.Join(util.GetAppProvider().ConfigFolder(), "i18n", "zh-cn.yaml")
	_, fErr := os.Stat(transFile)

	if fErr != nil {
		util.GetLogProvider().Info(context.Background(), transFile, nil)
		c.Json500Interface(api_error.ResponseIntervalServerError.SetMessage("验证翻译文件丢失"))
		return
	}

	i18n.MustLoadTranslationFile(transFile)
	T, _ := i18n.Tfunc("zh-cn")

	var fieldErrs = make([]string, 0, len(errs))
	fieldMap := fieldMapInterface.GetFieldMap()

	for _, v := range errs {
		mf := map[string]interface{}{}
		mf["field"] = ""
		if v, ok := fieldMap[v.Field()]; ok {
			mf["field"] = v //字段是什么
		}
		mf["value"] = v.Value()    //现在的值是什么
		mf["sValue"] = v.Param()   //限制在什么范围的值 , min=100, v.param=100
		fieldErr := T(v.Tag(), mf) //返回的提示错误， 如：  姓名不能为空

		fieldErrs = append(fieldErrs, fieldErr)
	}

	c.Json400Interface(api_error.ResponseParamError.SetMessage(strings.Join(fieldErrs, "\n")))
}
